package org.jiucheng.magpiebridge.manager.datasource;

import java.text.MessageFormat;

import org.jiucheng.ioc.annotation.Component;
import org.jiucheng.ioc.annotation.Value;
import org.jiucheng.magpiebridge.util.Cfg;
import org.jiucheng.orm.PoolDataSource;

@Component("dataSource")
public class H2DataSource extends PoolDataSource {
    
    @Value("h2.driverClass")
    private String driverClass;
    @Value("h2.url")
    private String url;
    @Value("h2.username")
    private String username;
    @Value("h2.password")
    private String password;
    @Value("h2.minActive")
    private Integer minActive;
    @Value("h2.maxActive")
    private Integer maxActive;
    @Value("h2.maxWait")
    private Long maxWait;
    
    private boolean urlReplaced = false;

    @Override
    public String getDriverClass() {
        return driverClass;
    }

    @Override
    public String getUrl() {
        if (urlReplaced) return url;
        return url(url);
    }
    
    private synchronized String url(String url) {
        if (urlReplaced) return this.url;
        this.url = url.replace("#DATABASE#", MessageFormat.format("{0}database", Cfg.baseDir()));
        urlReplaced = true;
        return this.url;
    }

    @Override
    public String getUsername() {
        return username;
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public int getMinActive() {
        return minActive;
    }

    @Override
    public int getMaxActive() {
        return maxActive;
    }

    @Override
    public long getMaxWait() {
        return maxWait;
    }
}
